package com.lipy.ribbon.config;

import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.netflix.ribbon.RibbonClientName;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description:
 * @author: lipy
 * @create: 2020-06-16 22:59
 * micro-order配置 放在scanpackage 外面 通过
 *
 * 如果放在主启动扫描下 会变成全局配置
 **/
@Configuration
public class RibbonLoadbalanceMicroOrderConfig {

//    @RibbonClientName
    private String name = "micro-order";

    @Bean
    @ConditionalOnClass
    public IClientConfig defaultClientConfig(){
        DefaultClientConfigImpl defaultClientConfig = new DefaultClientConfigImpl();
        defaultClientConfig.loadProperties(name);
        defaultClientConfig.set(CommonClientConfigKey.MaxAutoRetries, 2);
        defaultClientConfig.set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2);
        defaultClientConfig.set(CommonClientConfigKey.ConnectTimeout, 2000);
        defaultClientConfig.set(CommonClientConfigKey.ReadTimeout, 4000);
        defaultClientConfig.set(CommonClientConfigKey.OkToRetryOnAllOperations, true);
        return defaultClientConfig;
    }


    @Bean
    public IRule ribbonRule(){
        // 轮训
        new RoundRobinRule();
        // 可以重试的轮训
        new RetryRule();
        //根据运行情况计算权重
        new WeightedResponseTimeRule();
        // 过滤掉故障实例，选择请求最少的实例
        new BestAvailableRule();

        return new RandomRule();
    }

    /*
     * 判断服务是否存活
     * 不建议使用
     * */
//    @Bean
    public IPing iPing() {
        //这个实现类会去调用服务来判断服务是否存活
        PingUrl pingUrl = new PingUrl();
//        pingUrl.setPingAppendString("/user/queryContent");
        return pingUrl;
    }

}
